import Lock from '../package/lock'
import TaroStorage from "@path/tool/storage"
import config from "../config"
import { userStore } from '@/store'
function newLock() {
  return new Lock({
    async getValue() {
      return TaroStorage.getLocalStorage('localToken')
    },
    async setValue(token) {
      TaroStorage.setLocalStorage('localToken', token, config.tokenCatcheTime)
    },
    async clearValue() {
      TaroStorage.removeLocalStorage('localToken')
    },
  })
}
export const lock = { current: newLock() }
const wrapper = { current: Lock.createLockWrapper(lock.current) }

/**获取token失败，重置请求锁，清空用户数据，跳转到首页 */
function logout() {
  lock.current = newLock()
  wrapper.current = Lock.createLockWrapper(lock.current)
  userStore.logout()
}

/**获取token的请求接口 */
function onToken(): Promise<string> {
  return new Promise((resolve, reject) => {
    userStore.refreshToken().then((res) => {
      resolve(res.token)
    }).catch(() => {
      logout()
      reject()
    })
  })
}
export default async function (ctx, next) {
  if (ctx.request.skipToken === true) {
    const _obj = {
      ...(ctx.request?.header || {}),
    }
    if (userStore.userInfo?.token) {
      _obj["token"] = userStore.userInfo?.token
    }
    ctx.request["header"] = _obj
    return next()
  } else {
    // wrapper 会将所有请求拦截在这里，直到获取到 token 之后才放行
    const token = await wrapper.current(onToken)
    ctx.request["header"] = {
      ...(ctx.request?.header || {}),
      "token": token
    }
    await next()
  }
}
